package com.todo.server.DAO.action;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.todo.server.DAO.action.model.ActionDAO;
import com.todo.orm.action.Action;
import com.todo.util.HibernateUtil;

public class ActionDAOImpl extends RemoteServiceServlet implements ActionDAO {

	/**
	 * 
	 */
	private static final long serialVersionUID = 9145755684004500951L;

	public void addAction(Action action) {
		Session session = null;
		try {
			session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			session.persist(action);
			session.getTransaction().commit();

		} catch (Exception e) {
			System.err.println("Error --->" + e.getMessage());
			if (session.getTransaction() != null) {
				session.getTransaction().rollback();
			}
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}

	}

	public void updateAction(Action action) {
		Session session = null;
		try {
			session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			session.update(action);
			session.getTransaction().commit();

		} catch (Exception e) {
			System.err.println("Error --->" + e.getMessage());
			if (session.getTransaction() != null) {
				session.getTransaction().rollback();
			}
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}

	}

	public void deleteAction(Action action) {
		Session session = null;
		try {
			session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			session.delete(action);
			session.getTransaction().commit();

		} catch (Exception e) {
			System.err.println("Error --->" + e.getMessage());
			if (session.getTransaction() != null) {
				session.getTransaction().rollback();
			}
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}

	}

	public Action getActionById(int id) {
		Session session = null;
		Action action = null;
		try {
			session = HibernateUtil.getSessionFactory().openSession();
			action = (Action) session.load(Action.class, id);
		} catch (Exception e) {
			System.err.println("Error --->" + e.getMessage());
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}
		return action;
	}

	public List<Action> getAllActions() {
		Session session = null;
	    List<Action> actions = new ArrayList<Action>();
	    try {
	      session = HibernateUtil.getSessionFactory().openSession();
	      actions = session.createCriteria(Action.class).list();
	    } catch (Exception e) {
	    	System.err.println("Error --->" + e.getMessage());
	    } finally {
	      if (session != null && session.isOpen()) {
	        session.close();
	      }
	    }
	    return actions;
	}

}
